<?php
/**
 * Created by PhpStorm.
 * User: GadflyBSD
 * Date: 14-7-9
 * Time: 上午9:12
 */
namespace Common\Controller;
use Think\Controller;

class ToolController extends Controller {
	protected $uc;

	public function _initialize(){
		Vendor('Discuz.Client');
		$this->uc = new \Client();
	}

	public function login(){
		if(IS_AJAX && IS_POST && checkToken()){
			$this->ajaxReturn($this->uc->login($_POST['username'], $_POST['password']));
		}else{
			$this->error('非法请求');
		}
	}

	public function logout(){
		if(IS_AJAX){
			$this->ajaxReturn($this->uc->logout());
		}else{
			$this->error('非法请求');
		}
	}

	public function register(){
		if(IS_AJAX && IS_POST && checkToken()){
			$this->ajaxReturn($this->uc->register($_POST['username'], $_POST['password'], $_POST['email']));
		}else{
			$this->error('非法请求');
		}
	}

	public function checkLogin(){
		if(IS_AJAX){
			$this->ajaxReturn($this->uc->check_login());
		}else{
			$this->error('非法请求');
		}
	}

	public function getAuthcode(){
		if(IS_AJAX){
		$array = (!in_array(C('DEFAULT_CHARSET'), array('utf-8', 'UTF-8')))?convert_encoding(session('auth'), C('DEFAULT_CHARSET'), "UTF-8"):session('auth');
			$this->ajaxReturn($array);
		}else{
			$this->error('非法请求');
		}
	}

	public function verifyImg(){
		$Verify = new \Think\Verify();
		if(IS_AJAX && IS_POST){
			header('Content-Type: application/json; charset=utf-8');
			if($Verify->check($_POST['vdcode']))
				echo 'true';
			else
				echo 'false';
		}else{
			$Verify->useCurve = false;
			$Verify->entry();
		}
	}

	public function upload(){
		$targetFolder = 'data/upload'; // Relative to the root
		if(!empty($_FILES)){
			$tempFile = $_FILES['Filedata']['tmp_name'];
			$targetPath = $_SERVER['DOCUMENT_ROOT'].$targetFolder.$_POST['path'];
			$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
			if(!file_exists($targetPath)){
				mkdirs(str_replace('//','/',$targetPath), 0755, true);
			}
			$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
			$fileParts = pathinfo($_FILES['Filedata']['name']);

			if (in_array($fileParts['extension'],$fileTypes)) {
				move_uploaded_file($tempFile,$targetFile);
				header('Content-type: text/html; charset=UTF-8');
				echo json_encode(array('error' => 0, 'url' => $targetFolder.$_POST['path'].$_FILES['Filedata']['name']));
			} else {
				echo 'Invalid file type.';
			}
		}else{
			echo json_encode(array('error' => 1, 'url' => 'sdfgsdgsdg'));
		}
	}
}